const webpack = require('webpack');
const path = require('path');
const fs = require('fs')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const BACKEND_ENV = process.env.BACKEND_ENV || 'localhost'; // 后台服务器环境
const WEBPACK_MODE = process.env.WEBPACK_MODE || 'development'; // webpack的mode配置
const SOURCEMAP = process.env.SOURCEMAP === 'false' ? false : 'cheap-module-eval-source-map'; // source-map类型
const isWDS = /webpack-dev-server/.test(process.argv[1]); // 是否使用webpack-dev-server
const outputDir = path.resolve(__dirname, 'dist');
const pages = fs.readdirSync('./src/pages', { withFileTypes: true }).reduce((prev, dirent) => {
  dirent.isDirectory() && prev.push(dirent.name);
  return prev;
}, []);
console.log('BACKEND_ENV = ', BACKEND_ENV);
console.log('WEBPACK_MODE = ', WEBPACK_MODE);
console.log('SOURCEMAP = ', SOURCEMAP);
console.log('isWDS = ', isWDS);
console.log('outputDir = ', outputDir);

const config = {
  mode: WEBPACK_MODE,

  devtool: SOURCEMAP,

  entry: () => pages.reduce((prev, cur) => {
    prev[cur] = './src/pages/' + cur + '/index.js';
    return prev;
  }, {}),

  resolve: {
    extensions: ['.js'],
    alias: {
      img: path.resolve(__dirname, './src/assets/images'),
      libs: path.resolve(__dirname, './src/libs'),
      _libs: path.resolve(__dirname, './src/_libs'),
      components: path.resolve(__dirname, './src/components'),
    }
  },

  output: {
    path: outputDir,
    filename: '[name].js' + (isWDS ? '' : '?[chunkhash:7]'), // 模块热替换不能使用chunkhash，而且webpack-dev-server也无需使用hash
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, './src'),
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react'],
            plugins: [
              '@babel/syntax-dynamic-import',
              '@babel/plugin-proposal-class-properties',
              '@babel/plugin-proposal-object-rest-spread',
            ]
          }
        }
      },
      {
        test: /\.css$/,
        include: path.resolve(__dirname, './src'),
        exclude: [
          path.resolve(__dirname, './src/components')
        ],
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
      {
        test: /\.css$/,
        include: [
          path.resolve(__dirname, './src/components')
        ],
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: '[local]-[hash:base64:5]'
              }
            }
          },
          'postcss-loader'
        ],
      },
      {
        test: /\.(png|jpe?g|gif|svg|ttf|eot|woff|woff2)$/,
        loader: 'file-loader',
        options: {
          publicPath: '/',
          name: '[contenthash:7].[ext]',
          esModule: false,
        }
      },
      {
        test: /\.(html)$/,
        use: 'html-loader',
      },
    ]
  },

  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      'BACKEND_ENV': JSON.stringify(BACKEND_ENV),
      'WEBPACK_MODE': JSON.stringify(WEBPACK_MODE),
    }),
    new CopyWebpackPlugin([{
      from: './public',
      ignore: ['README.md']
    }]),
    ...pages.map(
      page => new HtmlWebpackPlugin({
        filename: page + '.html',
        template: './src/pages/' + page + '/index.html',
        chunks: [page],
      })
    ),
  ],

  devServer: {
    contentBase: outputDir, // webpack服务器根目录
    host: '0.0.0.0',
    disableHostCheck: true,
    port: 7000,
    useLocalIp: true,
    open: true,
  },

  optimization: {
    splitChunks: {
      chunks: 'all',
      // maxSize: isWDS ? 0 : 300000, // chunk的最大限制
    },
    minimizer: [
      new TerserJSPlugin(),
    ]
  },
};

module.exports = config;
